/**
 * @author 0283000115
 * @date 2018年3月3日-上午10:51:40
 */
package com.zte.claa.inficombo.csa.app.controller;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;

import com.zte.claa.inficombo.csa.app.controller.ret.ApiResult;
import com.zte.claa.inficombo.csa.app.service.token.CSAToken;
import com.zte.claa.inficombo.csa.app.service.token.CSATokenService;

/**
 * @author 0283000115
 * 
 * 基础控制器类，主要负责完成token验证等公共流程，以及提供相关公共方法.
 */

@Controller
public class BaseController {
	private Logger logger = LoggerFactory.getLogger(BaseController.class);
	
	@Autowired
	private CSATokenService tokenService;

	/**
	 * 检查token是否有效
	 * 
	 * @param token
	 * @throws Exception
	 * @return token中包括的userName, 设置到data域.
	 */
	public ApiResult<?> checkToken(String tokenStr) {
		logger.info("checkToken: tokenStr="+tokenStr);
		ApiResult<String> ret = new ApiResult<String>();
		ret.setData(null);
		ret.setResult(ApiResult.RET_INVALID_TOKEN);
		try{
			if(tokenStr == null || tokenStr.trim().equals("")){
				ret.setRemark("令牌为空！");
				return ret;
			}
			// 1.令牌校验.
			CSAToken token = null;
			try{			
				token = this.tokenService.parseApiToken(tokenStr);
			}catch(Exception e){
				logger.error("令牌解析错误！", e);
				ret.setRemark("令牌格式非法！");
				return ret;
			}
			this.tokenService.checkToken(token);
			ret.setResult(ApiResult.RET_SUCC);
			ret.setData(token.getUser());
			ret.setRemark("令牌验证通过.");
		}catch(Exception e){
			ret.setRemark(e.getMessage());
		}
		return ret;		
	}
	
	/**
	 * 从request请求中获取json字符串
	 * 
	 * @param request
	 * @return
	 */
	protected String getJsonParam(HttpServletRequest request) throws Exception {
		BufferedReader br = null;
		ServletInputStream in = null;
		try {
			in = request.getInputStream();
			br = new BufferedReader(new InputStreamReader(in, "utf-8"));
			StringBuffer sb = new StringBuffer("");
			String temp;
			while ((temp = br.readLine()) != null) {
				sb.append(temp);
			}
			return sb.toString();
		} finally {
			if(in != null){
				try{
					in.close();					
				}catch(Exception err){}
				in = null;
			}
			if (br != null) {
				try{
					br.close();					
				}catch(Exception e){}
				br = null;
			}
		}
	}
	
	/**
	 * 异常处理
	 * 
	 * @param e
	 * @return
	 */
	@ExceptionHandler(Exception.class)
    public ApiResult<String> handleException(Exception e) {
        logger.error(e.getMessage(), e);
        ApiResult<String> ret = new ApiResult<String>();
        ret.setData(null);
        ret.setRemark("服务端异常: "+e.getMessage());
        ret.setResult(ApiResult.RET_FAIL);
        return ret;
    }
}
